<?
define('DIRECTORY', realpath(dirname(__FILE__)) . '/../examples/demo');
define('WEB_DIRECTORY', '/examples/demo');
define('DEFAULT_PRIVILEGES',0777);
define('THUMBS_FOLDER','.thumbs');
define('THUMBS_WIDTH',100);
define('THUMBS_HEIGHT',100);

session_start();
header("Cache-control: private");
//error_reporting(0);

$params = $_REQUEST;
//$params['globalId'] - идентификатор уникальности связки с клиентом;

if (!isset($params['action'])) {
	if (isset($params["name"])) {
		$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
		$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
		$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

		$fileName = preg_replace('/[^\w\._]+/', '', $fileName);

		if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
			$contentType = $_SERVER["HTTP_CONTENT_TYPE"];
	
		if (isset($_SERVER["CONTENT_TYPE"]))
			$contentType = $_SERVER["CONTENT_TYPE"];
		if (strpos($contentType, "multipart") !== false) {
			if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
				// Open temp file
				$out = fopen(DIRECTORY . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
				if ($out) {
					// Read binary input stream and append it to temp file
					$in = fopen($_FILES['file']['tmp_name'], "rb");
	
					if ($in) {
						while ($buff = fread($in, 4096))
							fwrite($out, $buff);
					} else
						die('{"jsonrpc" : "2.0", error" : {"code": "100"}, "id" : "id"}');
					fclose($in);
					fclose($out);
					@unlink($_FILES['file']['tmp_name']);
					$path = WEB_DIRECTORY . DIRECTORY_SEPARATOR . $fileName;
					die('{"jsonrpc" : "2.0", "result" : {"id" : "'.$path.'", "name": "'.$fileName.'", path: "'.$path.'"}, "id": "id"}');
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": "100"}, "id" : "id"}');
			} else
				die('{"jsonrpc" : "2.0", "error" : {"code": "100"}, "id" : "id"}');
		} else {
			// Open temp file
			$out = fopen(DIRECTORY . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
			if ($out) {
				// Read binary input stream and append it to temp file
				$in = fopen("php://input", "rb");
	
				if ($in) {
					while ($buff = fread($in, 4096))
						fwrite($out, $buff);
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": "100"}, "id" : "id"}');
	
				fclose($in);
				fclose($out);
				$path = WEB_DIRECTORY . DIRECTORY_SEPARATOR . $fileName; 
				die('{"jsonrpc" : "2.0", "result" : {"id" : "'.$path.'", "name": "'.$fileName.'", path: "'.$path.'"}, "id" : "id"}');
			} else
				die('{"jsonrpc" : "2.0", "error" : {"code": "100"}, "id" : "id"}');
		}
	} else {
		die();
	}
	die();
}
$action = $params['action'];

switch ($action) {
	case "get_images" :
		$data=array();
		foreach (new DirectoryIterator(DIRECTORY) as $file){
			if($file->isDot() || $file->isDir()) continue;
			if (isset($params['mode']) && $params['mode']=='images'){ 
				$pathinfo = pathinfo($file->getFileName());
				if(!in_array($pathinfo['extension'], $ext_images)){
					continue;
				}
			}
			$path = WEB_DIRECTORY . DIRECTORY_SEPARATOR . $file->getFileName(); 
			$item = array(
				'name' => $file->getFileName(),
				'path'=> $path,
				'id' => $path
			);
			if (isset($params['mode']) && $params['mode']=='thumbs') {
				$thumb_name = $path . DIRECTORY_SEPARATOR . THUMBS_FOLDER . DIRECTORY_SEPARATOR . $file->getFileName() .'.jpg';
				if (file_exists($thumb_name) && $file->getMTime()<filemtime($thumb_name)) {
					$item['thumb_path'] = str_replace(DIRECTORY,WEB_DIRECTORY,$thumb_name);
				}
			}
			$data[] = $item;
			
		}
		die('{"jsonrpc" : "2.0", "result" : '.json_encode($data).', "id" : "id"}');
		break;
	case "rename_image" :
		if ($params['id'] && $params['name']) {
			$path = str_replace(WEB_DIRECTORY,DIRECTORY,$params['id']);
			$dest = str_replace(basename($path),$params['name'],$path);
			if (rename($path, $dest)) {
				@chmod($dest, DEFAULT_PRIVILEGES);
				die('{"jsonrpc" : "2.0", "result" : {"id":"'.$params['id'].'"}, "id" : "id"}');
			} else {
				die('{"jsonrpc" : "2.0", "error" : {"code": "120"}, "id" : "id"}');
			}
		} else {
			die('{"jsonrpc" : "2.0", "error" : {"code": "120"}, "id" : "id"}');
		}
		break;
	case "delete_image" :
		if ($params['id']) {
			$path = str_replace(WEB_DIRECTORY,DIRECTORY,$params['id']);
			if (@unlink($path)) {
				die('{"jsonrpc" : "2.0", "result" : {"id":"'.$params['id'].'"}, "id" : "id"}');
			} else {
				die('{"jsonrpc" : "2.0", "error" : {"code": "110"}, "id" : "id"}');
			}
		} else {
			die('{"jsonrpc" : "2.0", "error" : {"code": "110"}, "id" : "id"}');
		}
		break;
	case "save_order":
			//die('{"jsonrpc" : "2.0", "result" : {}, "id" : "id"}');
			die('{"jsonrpc" : "2.0", "error" : {"code": "140"}, "id" : "id"}');
		break;
}